/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package tletlis.network;


import java.io.*;
import java.util.*;
import java.net.*;

/**
 * A Threaded class that together with the classes SendMessage and Server will
 * act as a Server on a Client-Server network.
 * The StreamListener that will listen after messages from a given client.
 * When a new message is recieved a new SendMessage object will be created that
 * will send the recived messages to the other clients.
 * @author Max
 */
public class StreamListener extends Thread {

    /**
     * The client that can send messages to StreamListener
     */
    private Socket client;

    /**
     * The server that contains the clientSocketList
     */
    private Server server;

    /**
     * The constructor initializes values
     * and starts a new thread.
     * Creates a new StreamListener object.
     * 
     * @param client
     * @param server
     */
    public StreamListener(Socket client,Server server){
        this.client=client;
        this.server= server;
        this.start();
    }

    @Override
    /**
     * Overidden method that listens after messgaes on stream. When a new message is
     * recieved a new SendMessage object will be created.
     */
    public void run(){
        try {
            DataInputStream in = new DataInputStream( client.getInputStream()) ;
           
            
            while(client.isConnected()){

           
                  
                    String s=in.readUTF();
                    System.out.println(s);

                    //Get the list of connected clients from server and remove
                    //the client that will send the message (so that message doesn't return to sender)
                    List<Socket> clientList = server.getClientSocketList();
                    clientList.remove(client);
                    new SendMessage(s, clientList);
                    
            }

        } catch (IOException ex) {
            System.out.println("IOException in StreamListener class");
        }
        

    }
}
